<!--
 * @Descripttion: 新增房间-组件
 * @version: 1.0
 * @Author: 狸猫
 * @Date: 2023-10-26 17:16:01
 * @LastEditors: 狸猫
 * @LastEditTime: 2023-12-15 14:21:59
-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      :before-close="close"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="form"
      >
        <el-form-item label="所属地区" prop="region">
          <!-- v-if重新渲染解决不回显问题 -->
          <el-cascader
            v-if="reRender"
            ref="areaPicker"
            v-model="form.region"
            :props="areaProps"
            :show-all-levels="false"
            @change="handleChangeArea"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="楼盘、楼栋、单元"
          label-width="130"
          prop="houseInfo"
        >
          <el-cascader
            v-model="form.houseInfo"
            ref="houseInfo"
            :props="{
              value: 'id',
              label: 'name',
            }"
            :options="estateList"
            @change="handleChange"
            @visible-change="checkedRegion"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="所在楼层" prop="floors">
          <el-select
            v-model="form.floors"
            placeholder="请选择"
            @visible-change="checkedHouseInfo"
          >
            <el-option
              v-for="dict in floorList"
              :key="dict.value"
              :label="dict"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋类型" prop="houseNature">
          <el-select v-model="form.houseNature" placeholder="请选择" clearable>
            <el-option
              v-for="dict in dict.type.dict_house_nature"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房型类型" prop="houseType">
          <el-select v-model="form.houseType" placeholder="请选择" clearable>
            <el-option
              v-for="dict in dict.type.dict_house_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="是否线上出租"
          label-width="100"
          prop="onlineRentalType"
        >
          <el-radio-group v-model="form.onlineRentalType">
            <el-radio
              v-for="dict in dict.type.dict_online_rental_type"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否合租" label-width="100" prop="estateType">
          <el-radio-group v-model="form.shareFlatType">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="面积" prop="houseArea">
          <el-input
            type="number"
            v-model="form.houseArea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="户型" prop="roomType">
          <el-select v-model="form.roomType" placeholder="请选择" clearable>
            <el-option
              v-for="dict in dict.type.dict_room_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="朝向" prop="houseOrientation">
          <el-input v-model="form.houseOrientation" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="产权类型" prop="housePropertyType">
          <el-select
            v-model="form.housePropertyType"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.dict_room_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产权所有人" prop="housePropertyOwner">
          <el-select
            v-model="form.housePropertyOwner"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.dict_room_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="是否为智能设备"
          label-width="100"
          prop="smartFurnitureType"
        >
          <el-radio-group v-model="form.smartFurnitureType">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="水表号" prop="waterMeterNumber">
          <el-input
            type="number"
            v-model="form.waterMeterNumber"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="电表号" prop="electricMeterNumber">
          <el-input
            type="number"
            v-model="form.electricMeterNumber"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="燃气表号" prop="gasMeterNumber">
          <el-input
            type="number"
            v-model="form.gasMeterNumber"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="房屋管理员" prop="houseManagerId">
          <el-select
            v-model="form.houseManagerId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.dict_house_nature"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联物业" prop="propertyId">
          <el-select v-model="form.propertyId" placeholder="请选择">
            <el-option
              v-for="item in dict.type.dict_house_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        class="avatar-uploader"
        action="/api/common/upload"
        :show-file-list="false"
        :auto-upload="true"
        :headers="headers"
        :on-success="onSuccess"
        :on-remove="onRemove"
        :accept="'image/*'"
      >
        <img v-if="form.houseQrCode" :src="form.houseQrCode" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <el-row class="flex align-center" style="margin: 20px 0">
        房屋设施
        <i
          class="el-icon-circle-plus"
          style="
            color: #66b1ff;
            font-size: 24px;
            cursor: pointer;
            margin-left: 8px;
          "
          @click="addfacilities"
        ></i>
      </el-row>

      <el-row
        :gutter="6"
        v-for="(item, index) in form.facilitiesItems"
        :key="index"
        style="margin-bottom: 10px"
      >
        <el-col :span="6">
          <el-select v-model="item.facilitiesId" placeholder="请选择房屋设施">
            <el-option
              v-for="(item, index) in facilitiesMap"
              :key="index"
              :label="item.facilitiesName"
              :value="item.facilitiesId"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" style="display: flex; align-items: center">
          <span>数量：</span>
          <el-input
            v-model.number="item.num"
            placeholder="请输入"
            type="number"
          ></el-input>
        </el-col>
        <el-col :span="6" style="display: flex; align-items: center">
          <span>单价：</span>
          <el-input
            v-model.number="item.facilitiesPrice"
            placeholder="请输入"
            type="number"
          ></el-input>
        </el-col>
        <el-col :span="1" style="display: flex; align-items: center">
          <!-- <el-radio-group v-model="item.facilitiesState">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">已损坏</el-radio>
          </el-radio-group> -->
          <i
            class="el-icon-remove-outline"
            style="
              color: #e63f32;
              font-size: 24px;
              margin-left: 20px;
              margin-top: 6px;
              cursor: pointer;
            "
            @click="delfacilities(index)"
          ></i>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
function filterUnit(id, arr) {
  for (const item of arr) {
    if (item.id == id) return item;
    if (item.children && item.children.length > 0) {
      const _item = filterUnit(id, item.children);
      if (_item) return _item;
    }
  }
}
import { listFacilities } from "@/api/house/unmount";
import { addRoom, getRoom, updateRoom } from "@/api/house/room";
import { listArea } from "@/api/system/config";
import { listEstateArray } from "@/api/house/estate";
import { getToken } from "@/utils/auth";
export default {
  name: "roomAdd",
  dicts: [
    "dict_house_nature",
    "dict_house_type",
    "dict_online_rental_type",
    "dict_room_type",
  ],
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    roomId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      reRender: false,
      headers: {
        Authorization: `Bearer   ` + getToken(),
      },
      floorList: [],
      //楼盘列表
      estateList: [],
      areaOptions: [],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      form: {
        floors: "",
        estateId: "",
        facilitiesItems: [],
        subordinateHouseList: [],
        roomNumber: null,
        onlineRentalType: "0",
        shareFlatType: "0",
        smartFurnitureType: 0,
        housePropertyType: null,
        houseOrientation: null,
        roomType: null,
        houseManagerId: null,
        propertyId: null,
        region: [],
        houseInfo: [],
      },
      areaProps: {
        lazy: true,
        // emitPath: false,
        lazyLoad(node, resolve) {
          listArea({ level: node.level + 1, parentId: node.value }).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 4,
              }));
              resolve(areas);
            }
          );
        },
      },
      rules: {
        region: [{ required: true, message: "请选择地区", trigger: "change" }],
        houseInfo: [
          {
            required: true,
            message: "请选择楼盘、楼栋、单元",
            trigger: "change",
          },
        ],
        houseNature: [
          { required: true, message: "请选择房屋类型", trigger: "change" },
        ],
        houseType: [
          { required: true, message: "请选择房型类型", trigger: "change" },
        ],
        onlineRentalType: [
          { required: true, message: "请选择是否线上出租", trigger: "change" },
        ],
        roomNumber: [
          { required: true, message: "请输入房间号", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        houseArea: [{ required: true, message: "请输入面积", trigger: "blur" }],
        roomType: [
          { required: true, message: "请选择户型", trigger: "change" },
        ],
        houseOrientation: [
          { required: true, message: "请输入朝向", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        housePropertyType: [
          { required: true, message: "请选择产权类型", trigger: "change" },
        ],
        housePropertyOwner: [
          { required: true, message: "请选择产权所有人", trigger: "change" },
        ],
        smartFurnitureType: [
          {
            required: true,
            message: "请选择是否为智能设备",
            trigger: "change",
          },
        ],
        houseManagerId: [
          { required: true, message: "请选择房屋管理员", trigger: "change" },
        ],
        propertyId: [
          { required: true, message: "请选择关联物业", trigger: "change" },
        ],
        floors: [{ required: true, message: "请选择楼层", trigger: "change" }],
      },
      title: "新增房间",
      file: "",
    };
  },
  async created() {
    this.getfacilityList();
    if (this.roomId) {
      this.getRoomDetail();
      this.title = "编辑房间";
    } else {
      this.reRender = true;
    }
  },
  methods: {
    handleChange(e) {
      const checkedNodes = this.$refs["houseInfo"].getCheckedNodes();
      const ids = checkedNodes[0].path;
      const labels = checkedNodes[0].pathLabels;
      let floorList = [];
      let number = checkedNodes[0].data.number;
      let i = 1;
      while (i <= number) {
        floorList.push(i);
        i++;
      }
      this.floorList = floorList;
      this.form.estateId = ids[0];
      this.form.estateName = labels[0];
      this.form.buildingId = ids[1];
      this.form.buildingName = labels[1];
      this.form.unitId = ids[2];
      this.form.unitName = labels[2];
    },
    //检测是否选择区域
    checkedRegion(e) {
      if (this.form.region.length == 0 && e) {
        this.$modal.closeAll();
        this.$modal.msgError("请选择区域");
      }
    },
    checkedHouseInfo(e) {
      if (this.form.houseInfo.length == 0 && e) {
        this.$modal.closeAll();
        this.$modal.msgError("请选择楼盘");
      }
    },
    estateChange(e) {
      let data = this.estateList.find((item) => item.estateId === e);
      this.form.estateName = data.estateName;
    },

    /** 详情 */
    async getRoomDetail() {
      this.loading = true;
      await getRoom(this.roomId).then((response) => {
        let form = response.data;
        let region = [];
        region.push(response.data.provinceId);
        region.push(response.data.cityId);
        region.push(response.data.districtId);
        region.push(response.data.streetId);
        region.push(response.data.communityId);
        let houseInfo = [];
        houseInfo.push(response.data.estateId);
        houseInfo.push(response.data.buildingId);
        houseInfo.push(response.data.unitId);
        form.region = region;
        form.houseInfo = houseInfo;
        this.form = form;
        this.reRender = true;
      });
      await this.getlistEstate();
    },
    /** 查询楼盘列表 */
    getlistEstate() {
      this.loading = true;
      listEstateArray({ communityId: this.form.region[4] }).then((response) => {
        this.estateList = response;
        if (this.form.unitId) {
          let data = filterUnit(this.form.unitId, this.estateList);
          let floorList = [];
          let number = data.number;
          let i = 1;
          while (i <= number) {
            floorList.push(i);
            i++;
          }
          this.floorList = floorList;
        }
      });
    },
    //区域选择时间
    handleChangeArea(val) {
      const checkedNode = this.$refs["areaPicker"].panel.getNodeByValue(val);
      const ids = checkedNode.path;
      const labels = checkedNode.pathLabels;
      this.form.provinceId = ids[0];
      this.form.cityId = ids[1];
      this.form.districtId = ids[2];
      this.form.streetId = ids[3];
      this.form.communityId = ids[4];

      this.form.provinceName = labels[0];
      this.form.cityName = labels[1];
      this.form.districtName = labels[2];
      this.form.streetName = labels[3];
      this.form.communityName = labels[4];
      this.form.estateId = "";
      this.getlistEstate();
    },

    //删除设施
    delfacilities(index) {
      this.form.facilitiesItems.splice(index, 1);
    },
    //添加设施
    addfacilities() {
      this.form.facilitiesItems.push({
        facilitiesId: null,
        facilitiesPrice: null,
        facilitiesState: 1,
      });
    },
    /** 查询设施列表 */
    getfacilityList() {
      listFacilities().then((response) => {
        this.facilitiesMap = response.data;
      });
    },
    onSuccess(response, file, fileList) {
      this.$set(this.form, "houseQrCode", response.url);
      //this.form.houseQrCode = response.url;
    },
    onRemove() {
      this.form.houseQrCode = "";
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.roomId != "") {
            updateRoom(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.close();
            });
          } else {
            addRoom(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.close();
            });
          }
        }
      });
    },
    cancel() {
      this.close();
    },
    close() {
      this.$emit("closeeldialog");
    },
  },
};
</script>
<style lang="scss" scoped>
.form {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
.el-input::v-deep {
  width: 217px;
}
.avatar-uploader::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
